package op2;

class Philosopher implements Runnable {
    private final Object leftFork;
    private final Object rightFork;

    public Philosopher(Object leftFork, Object rightFork) {
        this.leftFork = leftFork;
        this.rightFork = rightFork;
    }
    @Override
    public void run() {
        try {
            String threadName = Thread.currentThread().getName();
            // 提取线程名称中的数字部分
            int philosopherNumber = Integer.parseInt(threadName.substring(3));
            if (philosopherNumber % 2 == 1) {
                synchronized (leftFork) {
                    System.out.println(threadName + "获取左筷子");
                    synchronized (rightFork) {
                        System.out.println(threadName + "获取右筷子");
                        System.out.println("哲学家开始就餐" + threadName);
                        Thread.sleep(1000);
                    }
                }
            } else {
                synchronized (rightFork) {
                    System.out.println(threadName + "获取右筷子");
                    synchronized (leftFork) {
                        System.out.println(threadName + " 获取左筷子");
                        System.out.println("哲学家开始就餐" + threadName);
                        Thread.sleep(1000);
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (NumberFormatException e) {
            System.err.println("线程名称格式错误: " + Thread.currentThread().getName());
            e.printStackTrace();
        }
    }
}

public class DiningPhilosophers {
    public static void main(String[] args) {
        Object[] forks = new Object[5];
        for (int i = 0; i < forks.length; i++) {
            forks[i] = new Object();
        }

        Philosopher[] philosophers = new Philosopher[5];
        philosophers[0] = new Philosopher(forks[4], forks[0]);
        philosophers[1] = new Philosopher(forks[0], forks[1]);
        philosophers[2] = new Philosopher(forks[1], forks[2]);
        philosophers[3] = new Philosopher(forks[2], forks[3]);
        philosophers[4] = new Philosopher(forks[3], forks[4]);

        Thread[] threads = new Thread[5];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(philosophers[i], "哲学家" + (i + 1));
            threads[i].start();
        }
    }
}